﻿using System.IO;
using System.Xml.Serialization;

namespace DCS.Service
{
    ///<summary>
    ///</summary>
    public class Settings
    {
        private static readonly string Path = System.IO.Path.Combine("C:",
                                                                     "DCS Server Settings.xml");
        private static Settings instance;
        ///<summary>
        /// Адрес центрального DCS сервера
        ///</summary>
        public string CentralServer { get; set; }

        private Settings() { }

        ///<summary>
        /// Публичное поле для доступа к Singleton-объекту
        ///</summary>
        public static Settings Instance
        {
            get { return instance ?? (instance = Load()); }
        }

        ///<summary>
        /// Загружает экземпляр класса настроек из файла
        ///</summary>
        ///<returns></returns>
        private static Settings Load()
        {
            try
            {
                var xs = new XmlSerializer(typeof(Settings));

                Settings clientModel;

                using (var reader = File.OpenText(Path))
                {
                    clientModel = xs.Deserialize(reader) as Settings;
                }

                return clientModel;
            }
            catch
            {
                return new Settings();
            }
        }

        ///<summary>
        /// Сохрянят текущие настройки в файл
        ///</summary>
        public void Save()
        {
            var xs = new XmlSerializer(GetType());
            var writer = File.CreateText(Path);

            xs.Serialize(writer, this);

            writer.Flush();
            writer.Close();
        }
    }
}
